package com.taotao.rest.service.impl;

import com.taotao.mapper.TbItemCatMapper;
import com.taotao.pojo.TbItemCat;
import com.taotao.pojo.TbItemCatExample;
import com.taotao.rest.pojo.CatNode;
import com.taotao.rest.pojo.ItemCatResult;
import com.taotao.rest.service.ItemCatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 李小磊 on 2017/3/25.
 */
@Service
public class ItemCatServiceImpl implements ItemCatService {
    @Autowired
    private TbItemCatMapper itemCatMapper;
    @Override
    public ItemCatResult getItemCatList() {
        List catList  =  getItemCatList(0l);
        ItemCatResult result = new ItemCatResult();
        result.setData(catList);
        return result;
    }

    private List getItemCatList(Long parentId) {
        TbItemCatExample example = new TbItemCatExample();
        example.createCriteria().andParentIdEqualTo(parentId);
        List<TbItemCat> list = itemCatMapper.selectByExample(example);
        List resultList = new ArrayList();
        int index =0;
        for (TbItemCat itemcat: list
             ) {
            if (index >= 14){
                break;
            }
            //是父节点
            if (itemcat.getIsParent()){
            CatNode node = new CatNode();
            node.setUrl("/products/"+itemcat.getId()+".html");
            if (itemcat.getParentId() == 0){
                node.setName("<a href='/products/"+itemcat.getId()+".html'>"+itemcat.getName()+"</a>");
                index++;
            }else {
                node.setName(itemcat.getName());
            }
            node.setItems(getItemCatList(itemcat.getId()));
            resultList.add(node);
            }else {
                String item = "/products/"+itemcat.getId()+".html|"+itemcat.getName();
                resultList.add(item);
            }

        }
        return resultList;
    }
}
